<?php 

namespace app\seller\event;

use app\common\model\Discount as DiscountModel;
use app\common\utils\JsonService;

class DiscountEvent{

    /*
    * 促销列表
    */
    public static function discountList($params){
        //$params = array_filter(request()->param());
        $page = ! empty($params['page']) && $params['page'] >= 1 ? $params['page'] : 1;
        $where = [];
        if($discount_id = isset($params['discount_id'])){
                    $where[] = ['discount_id','=',$params['discount_id']];
            }
            if($discount_name = isset($params['discount_name'])){
                    $where[] = ['discount_name','like',"%{$params['discount_name']}%"];
            }
            if($shop_id = isset($params['shop_id'])){
                    $where[] = ['shop_id','like',"%{$params['shop_id']}%"];
            }
            if($goods_id = isset($params['goods_id'])){
                    $where[] = ['goods_id','like',"%{$params['goods_id']}%"];
            }
             $condition = [
            'where' => $where,
            'order' => ['discount_id' => 'desc'],
                'paginate' => [
                'page' => $page,
                'query' => $params,
                'list_rows'=>20,
            ],
        ];
        $discount = DiscountModel::getPageAll($condition);
        return $discount;
    }


    /*
    * 新增促销
    */
    public static function createDiscount($data){
        if(!isset($data['goods_id'])){
            return JsonService::error('必须选择商品');
        }
        $start_time = strtotime($data['start_time'].' 00:00:00');
        $end_time = strtotime($data['end_time'].' 23:59:59');
        if($end_time < $start_time){
            return JsonService::error('结束时间不能小于开始时间');
        }
        $data['start_time'] = $start_time;
        $data['end_time'] = $end_time;

        try {
            DiscountModel::create($data);
        } catch (\Exception $ex) {
            return JsonService::error($ex->getMessage());
        }
        return JsonService::success();
    }

    /*
    * 更新促销
    */
    public static function updateDiscount($data){
        if(!isset($data['goods_id'])){
            return JsonService::error('必须选择商品');
        }
        $start_time = strtotime($data['start_time'].' 00:00:00');
        $end_time = strtotime($data['end_time'].' 23:59:59');
        if($end_time < $start_time){
            return JsonService::error('结束时间不能小于开始时间');
        }
        $data['start_time'] = $start_time;
        $data['end_time'] = $end_time;
        try {
            DiscountModel::updateOne($data, ['discount_id' => $data['discount_id']]);
        } catch (\Exception $ex) {
            return JsonService::error($ex->getMessage());
        }
        return JsonService::success();
    }


}

